package com.helloandroid

import android.app.Activity
import android.content.Intent
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.edit
import androidx.fragment.app.viewModels
import com.business.Analyse
import com.business.AnalyseKey
import com.cy.game.CyHomeActivity
import com.hby.game.HbyGame
import com.helloandroid.activitys.*
import com.helloandroid.ads.VideoAdUtil
import com.helloandroid.app.model.AppCache
import com.helloandroid.base.BaseFragment
import com.helloandroid.dialogs.AwardDialog
import com.helloandroid.dialogs.BigAwardDialog
import com.helloandroid.dialogs.LoadingDialog
import com.helloandroid.models.BsData
import com.helloandroid.models.ZouViewModel
import com.helloandroid.tools.*
import com.helloandroid.view.DashBoard
import com.helloandroid.vo.BoardInfo
import com.helloandroid.vo.HbyInfo
import com.helloandroid.vo.ZouConstants
import com.jf.game.JfGame
import com.zp.game.ZpGame
import dai.android.util.AndroidUtils
import dai.ui.UITweenModel
import dai.ui.moveBy
import dai.ui.repeat
import dai.ui.single.Delay
import dai.ui.single.MoveBy
import game.engine.base.CoreUtil
import java.util.*

class ZouzouFragment : BaseFragment() {

    // views
    lateinit var tvCount: TextView
    lateinit var dashBoard: DashBoard
    private lateinit var iv_coin_1: ImageView
    private lateinit var iv_coin_2: ImageView
    private lateinit var iv_coin_3: ImageView
    private lateinit var iv_dailyCoin: ImageView

    lateinit var tvLastHybTime:TextView

    lateinit var tvTargetBs: TextView
    lateinit var btnBoard: Button
    lateinit var tv_xinren: TextView
    lateinit var rlError: RelativeLayout

    lateinit var tvDistance: TextView
    lateinit var tvSpendTime: TextView
    lateinit var tvEnergy: TextView
    lateinit var ivBtnHby : ImageView

    val model: ZouViewModel by viewModels()
    private val tweenModel: UITweenModel by viewModels()

    var isReady = false
    var isHbyDataReady = false

    var mInfo:BoardInfo? = null
    var mHbyInfo: HbyInfo? = null

    private val throttleListeren = object: ThrottleClickListener() {
        override fun noDoubleClick(v: View?) {
            when(v?.id){
                // 跳转到天天红包赛
                R.id.btnTTHBS -> startToActivity(TianTianHongBaoActivity::class.java)

                //  补贴
                R.id.ibZaoWanDaKa -> startToActivity(ZaoWanDaKaActivity::class.java)
                R.id.ibHeShuiDaKa -> startToActivity(HeShuiDaKaActivity::class.java)
                R.id.ibChiFanBuTie -> startToActivity(ChiFanActivity::class.java)
                R.id.ibMeiRiYunDong -> startToActivity(MeiRiYunDongActivity::class.java)
                R.id.ibBuShuDaKa -> startToActivity(BuShuDaKaActivity::class.java)

                // 跳转到成语
                R.id.btnChengyu -> if (isReady)startToActivity(CyHomeActivity::class.java)

                // 红包雨
                R.id.ivBtnHby -> btnHbyClicked()

                // 转盘
                R.id.btnZhuanPan -> if (isReady)startToActivity(ZpGame::class.java)

                // 积福
                R.id.btnJiFu -> if (isReady)startToActivity(JfGame::class.java)

                // 步数打卡
                R.id.btnBs -> if (isReady)startToActivity(BuShuDaKaActivity::class.java)

                // 重新登陆
                R.id.btnReLogin -> btnReloginClicked()

            }
        }
    }

    override fun getLayoutResId() = R.layout.fragment_zouzou

    private fun <T : Activity> startToActivity(clz: Class<T>) {
        startActivity(Intent(activity, clz))
    }

    override fun initView(view: View) {
        tweenModel.startLoop()
        rlError = findViewById(R.id.rlError)
        tvCount = findViewById(R.id.tvCount)
        dashBoard = findViewById(R.id.dashBoard)
        iv_coin_1 = findViewById(R.id.iv_coin_1)
        iv_coin_2 = findViewById(R.id.iv_coin_2)
        iv_coin_3 = findViewById(R.id.iv_coin_3)
        iv_dailyCoin = findViewById(R.id.iv_dailyCoin)
        btnBoard = findViewById(R.id.btnBoard)
        tv_xinren = findViewById(R.id.tv_xinren)
        tvTargetBs = findViewById(R.id.tvTargetBs)
        tvTargetBs.text = "目标${AppUtil.user.bs_target}步"
        tvDistance = findViewById(R.id.tvDistance)
        tvEnergy = findViewById(R.id.tvEnergy)
        tvSpendTime = findViewById(R.id.tvSpendTime)
        tvLastHybTime = findViewById(R.id.tvLastHybTime)
        ivBtnHby = findViewById(R.id.ivBtnHby)

        findBtn(R.id.btnTTHBS).setOnClickListener(throttleListeren)
        findBtn(R.id.ibZaoWanDaKa).setOnClickListener(throttleListeren)
        findBtn(R.id.ibHeShuiDaKa).setOnClickListener(throttleListeren)
        findBtn(R.id.ibChiFanBuTie).setOnClickListener(throttleListeren)
        findBtn(R.id.ibMeiRiYunDong).setOnClickListener(throttleListeren)
        findBtn(R.id.ibBuShuDaKa).setOnClickListener(throttleListeren)

        findBtn(R.id.btnChengyu).setOnClickListener(throttleListeren)
        ivBtnHby.setOnClickListener(throttleListeren)

        findBtn(R.id.btnZhuanPan).setOnClickListener(throttleListeren)
        findBtn(R.id.btnJiFu).setOnClickListener(throttleListeren)

        // 跳转到 步数打卡
        findBtn(R.id.btnBs).setOnClickListener(throttleListeren)

        coinAnim(iv_coin_1)
        coinAnim(iv_coin_2)
        coinAnim(iv_coin_3)
        coinAnim(iv_dailyCoin)

        if (AppUtil.isLogin) {
            rlError.visibility = View.GONE
        } else {
            rlError.visibility = View.VISIBLE
            findBtn(R.id.btnReLogin).setOnClickListener(throttleListeren)
        }

        // for debug
        if (AppConfig.isDebug){
            AndroidUtils.showMem(requireActivity())
        }
    }

    private fun coinAnim(coin: View) {
        val move = MoveBy(1f,0f,20f)
                .moveBy(1f,0f,-20f)

        val time = CoreUtil.randomFloat(3f,6f) / 10f
        Delay(time).repeat(-1,move).runBy(coin,tweenModel)
    }

    ////=========== update UI
    private fun updateFreeCoin1(lastTime:Long){
        if (AppUtil.sysTime - lastTime >= GUtils.OneHourMs) {
            // 显示出来
            iv_coin_1.setImageResource(R.drawable.dd_coin_small)
            iv_coin_1.setOnClickListener {
                btnGetFreeCoin(ZouConstants.FreeCoin_1)
            }
        } else {
            iv_coin_1.setImageResource(R.drawable.dd_game_zhuan_small)
            iv_coin_1.setOnClickListener {
                startToActivity(ZpGame::class.java)
            }
        }
    }

    private fun updateFreeCoin2(lastTime:Long){
        if (AppUtil.sysTime - lastTime >= GUtils.OneHourMs) {
            // 显示
            iv_coin_2.setImageResource(R.drawable.dd_coin_small)
            iv_coin_2.setOnClickListener {
                btnGetFreeCoin(ZouConstants.FreeCoin_2)
            }
        } else {
            iv_coin_2.setImageResource(R.drawable.dd_game_chengyu_small)
            iv_coin_2.setOnClickListener {
                startToActivity(CyHomeActivity::class.java)
            }
        }
    }

    private fun updateFreeCoin3(lastTime:Long){
        if (AppUtil.sysTime - lastTime >= GUtils.TwoHourMs) {
            // 显示
            iv_coin_3.setImageResource(R.drawable.dd_coin_small)
            iv_coin_3.setOnClickListener {
                btnGetFreeCoin(ZouConstants.FreeCoin_3)
            }
        } else {
            iv_coin_3.setImageResource(R.drawable.dd_game_fu_small)
            iv_coin_3.setOnClickListener {
                startToActivity(MeiRiYunDongActivity::class.java)
            }
        }
    }

    private fun updateFreeCoin4(state:Int){
        // 0 表示还没领取
        // 1 表示已经领取
        // 每日红包奖励是否已经领了
        if (state < 1) {
            // 还没有领取
            iv_dailyCoin.setImageResource(R.drawable.dd_board_money_icon)
            iv_dailyCoin.setOnClickListener {
                if (AppUtil.serverConfig.dashboardDailyRedPacketVideo > 0){
                    // 播放广告
                    VideoAdUtil.playVideoAd(requireActivity()){success->
                        if (success){
                            Analyse.report(AnalyseKey.DashboardDailyRedPacketVideo)
                            btnGetFreeCoin(ZouConstants.FreeCoin_4)
                        }else{
                            AppUtil.toast("视频还未准备好!")
                        }
                    }
                }else{
                    btnGetFreeCoin(ZouConstants.FreeCoin_4)
                }
            }
        } else {
            iv_dailyCoin.setImageResource(R.drawable.dd_game_hby_small)
            iv_dailyCoin.setOnClickListener {
                if (AppUtil.isHbyCanPlay()){
                    startToActivity(HbyGame::class.java)
                }else{
                    AppUtil.toast("红包雨时间还没到!")
                }
            }
        }
    }

    private fun updateBoard(bsData:BsData){
        val bsAwardedCount = bsData.bsCount
        val awardId = ZouConstants.getIdByBsCount(bsAwardedCount)
        if (bsData.firstUsed < 1) {
            // 没有领取
            btnBoard.setBackgroundResource(R.drawable.btn_red)
            btnBoard.text = "首次金币奖励"
            tv_xinren.visibility = View.VISIBLE
            btnBoard.setOnClickListener {
                val dialog = BigAwardDialog(requireActivity())
                dialog.openCallback = this::getNewUserAward
                dialog.show()
            }
        } else {
            tv_xinren.visibility = View.INVISIBLE

            // 根据已经领取的去判断 当前可以领哪些
            val curBs = AppUtil.user.bs
            val stateAndValue = calBsAwardInfo(curBs, awardId)
            if (stateAndValue.first) {

                //  当前可以领的步数
                val bs = ZouConstants.getBSCount(awardId + 1)

                // 当前可以领取
                btnBoard.setBackgroundResource(R.drawable.btn_red)
                btnBoard.text = "${bs}步领取${stateAndValue.second}金币"
                btnBoard.setOnClickListener {
                    getBsStepAward(awardId + 1)
                }
            } else {
                // 当前不可以领取
                if (stateAndValue.second < 0) {
                    // 全部领完了
                    btnBoard.setBackgroundResource(R.drawable.dd_btn_gray)
                    btnBoard.text = "全部领取完毕"
                    btnBoard.setOnClickListener(null)
                } else {
                    //  下一次的步数
                    val bs = ZouConstants.getBSCount(awardId + 1)
                    btnBoard.setBackgroundResource(R.drawable.dd_btn_gray)
                    btnBoard.text = "${bs}步领取${stateAndValue.second}金币"
                    btnBoard.setOnClickListener {
                        AppUtil.toast("步数不够,请先完成步数再领取!")
                    }
                }
            }
        }
    }

    override fun initData() {

        if (AppUtil.isLogin) {
            fetchInfo()
        }

        model.startPerSecondTick(this::perSecondTick)
    }

    private fun perSecondTick(){
        if (!isReady){
            return
        }

        // TODO:每秒更新, 可以进行刷新状态和倒计时
        // 更新UI
        updateBuShu(AppUtil.user.bs)
        mInfo?.let {
            updateBoard(BsData(it.firstUsed,it.bsCount))
        }

        // 更新目标
        tvTargetBs.text = "目标${ AppUtil.user.bs_target}步"
    }

    // 领取步数奖励
    private fun getBsStepAward(idForServer:Int){
        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打开网络!")
            return
        }
        val bsCount = ZouConstants.getBSCount(idForServer)
        if (bsCount < 0){
            MyLog.elog("请求奖励的步数错误!")
            return
        }
        AppUtil.appViewModel().zouAwardStepCoin(bsCount)
        mInfo?.let {
            it.bsCount = bsCount
            updateBoard(BsData(it.firstUsed,it.bsCount))
        }
        val awardCoin = ZouConstants.StepMap[bsCount]!!
        showAwardDialog(awardCoin,AnalyseKey.BSStep_Video)

        Analyse.report(AnalyseKey.BSStep)
    }

    // 领取新用户奖励
    private fun getNewUserAward(){
        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打开网络!")
            return
        }

        if (AppUtil.serverConfig.newUserRedVideo > 0){
            // 看视频
            VideoAdUtil.playVideoAd(requireActivity()){success->
                if (success){
                    Analyse.report(AnalyseKey.NewUserFirstVideo)
                    realNewUserAward()
                }else{
                    AppUtil.toast("视频还没准备好!")
                }
            }
        }else{
            realNewUserAward()
        }
    }

    private fun realNewUserAward(){
        val awardCoin = 388
        AppUtil.appViewModel().zouNewUserAward(awardCoin)
        mInfo?.apply {
            firstUsed = 1
            updateBoard(BsData(firstUsed,bsCount))
        }
        Analyse.report(AnalyseKey.NewUser)
        showAwardDialog(awardCoin,AnalyseKey.NewUser_Video)
    }

    private fun showAwardDialog(coinCount:Int,reasonKey:String){
        val dialog = AwardDialog(this, coinCount)
        dialog.reasonKey = reasonKey
        dialog.show()
    }

    private fun initUI(){
        val info = mInfo!!
        updateFreeCoin1(info.cointime1)
        updateFreeCoin2(info.cointime2)
        updateFreeCoin3(info.cointime3)
        updateFreeCoin4(info.dailyCoinState)
        updateBoard(BsData(info.firstUsed,info.bsCount))
        updateBuShu(AppUtil.user.bs)

        val pref = MyApplication.getPerference(AppConfig.Pref_Local)
        val value = pref.getBoolean(AppConfig.KeyNewUserToastFlag,false)
        if (!value){
            // 首次
            pref.edit(commit = true){
                putBoolean(AppConfig.KeyNewUserToastFlag,true)
            }
            // 弹出来
            val dialog = BigAwardDialog(requireActivity())
            dialog.openCallback = this::getNewUserAward
            dialog.show()
        }
    }

    private fun fetchInfo() {
        model.getInfo {success,info->
            isReady = success
            if (isReady) {
                mInfo = info
                // 更新UI
                initUI()
                (activity as MainActivity).let {
                    if (!it.isHbyPending()){
                        it.checkComeFrom()
                    }
                }
            } else {
                AppUtil.toast("加载信息失败!!")
            }
        }

        model.getLastHbyTime{success,info->
            isHbyDataReady = success
            if (success){
                mHbyInfo = info
                MyLog.info("====== mHbyInfo:${mHbyInfo}")
                refreshBhyBtn()

                (activity as MainActivity).let {
                    if (it.isHbyPending()){
                        it.checkComeFrom()
                    }
                }
            }
        }
    }

    // 刷新 红包雨 按钮
    private fun refreshBhyBtn(){

        if (AppUtil.isHbyTodayCompleted()){
            tvLastHybTime.visibility = View.INVISIBLE
            ivBtnHby.setImageResource(R.drawable.dd_zou_hongbaoyu_gray)
            model.stopTick()
            return
        }else{
            tvLastHybTime.visibility = View.VISIBLE
            ivBtnHby.setImageResource(R.drawable.dd_zzou_hongbaoyu_btn)

            // 计算倒计时时间
            if (AppUtil.isHbyCanPlay()){
                tvLastHybTime.visibility = View.GONE
                tvLastHybTime.text = "已激活"
                if (model.tickRunning){
                    model.stopTick()
                }
            }else{
                tvLastHybTime.visibility = View.VISIBLE
                // 计算时间
                val ms = AppUtil.sysTime - mHbyInfo!!.lastTimeMs

                // 剩余时间
                var restTime = GUtils.TenMinutes - ms
                if (restTime < 0){
                    restTime = 0L
                }
                // 显示时间
                tvLastHybTime.text = MyTimeUtils.format_mmss(restTime)

                if (!model.tickRunning){
                    model.tick(this::refreshBhyBtn)
                }
            }
        }
    }

    // 返回 1. 如果可以领取  true, awardCoin
    //      2. 如果不能领取  false,nextAwardCoin
    private fun calBsAwardInfo(curBs: Int, awardId: Int): Pair<Boolean, Int> {

        // 不可以领取
        // case 1 全部领取完了
        // case 2 还没到达最终可以领取的
        if (awardId >= ZouConstants.StepMap.size - 1) {
            return false to -1   // case1
        }

        var idx = -1
        val keys = ZouConstants.StepMap.keys
        keys.forEachIndexed { index, num ->
            if (curBs < num) {
                return@forEachIndexed
            }
            idx = index
        }

        var bsKey = -1
        keys.forEachIndexed { index, i ->
            if (awardId + 1 == index) {
                bsKey = i
                return@forEachIndexed
            }
        }
        return if (awardId < idx) {
            // 可以领取, 领取的是 awardId + 1  所指向的值
            true to ZouConstants.StepMap[bsKey]!!
        } else {
            // 下一个即将要领取的是 award + 1
            false to ZouConstants.StepMap[bsKey]!!
        }
    }

    private fun btnGetFreeCoin(type: Int) {

        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打开网络!")
            return
        }

        Analyse.report(AnalyseKey.DashBoardCoin)

        // 1和2为小额
        // 3为大额
        // 4 也是金币
        when (type) {
            ZouConstants.FreeCoin_1 ->{
                // 小额
                var awardCoin = GUtils.randomInt(8,40)
                AppUtil.appViewModel().zouAwardFreeCoin(type,awardCoin)
                mInfo?.apply {
                    cointime1 = AppUtil.sysTime
                    updateFreeCoin1(cointime1)
                }
                showAwardDialog(awardCoin,AnalyseKey.DashBoardCoin_Video)
            }
            ZouConstants.FreeCoin_2 -> {
                // 小额
                var awardCoin = GUtils.randomInt(8,40)
                AppUtil.appViewModel().zouAwardFreeCoin(type,awardCoin)
                mInfo?.apply {
                    cointime2 = AppUtil.sysTime
                    updateFreeCoin2(cointime2)
                }
                showAwardDialog(awardCoin,AnalyseKey.DashBoardCoin_Video)
            }

            ZouConstants.FreeCoin_3 ->{
                //  大额
                var awardCoin = GUtils.randomInt(50,80)
                AppUtil.appViewModel().zouAwardFreeCoin(type,awardCoin)
                mInfo?.apply {
                    cointime3 = AppUtil.sysTime
                    updateFreeCoin3(cointime3)
                }
                showAwardDialog(awardCoin,AnalyseKey.DashBoardCoin_Video)
            }
            ZouConstants.FreeCoin_4->{
                var awardCoin = 88
                AppUtil.appViewModel().zouAwardFreeCoin(type,awardCoin)
                mInfo?.apply {
                    dailyCoinState = 1
                    updateFreeCoin4(dailyCoinState)
                }
                showAwardDialog(awardCoin,AnalyseKey.DashBoardCoin_Video)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (mHbyInfo != null){
            AppCache.hbyInfo?.let {
                mHbyInfo!!.lastTimeMs = it.lastTimeMs
                mHbyInfo!!.count = it.count
            }
            MyLog.elog("ZouFragment mHbyInfo:${mHbyInfo}")
            model.tick(this::refreshBhyBtn)
        }
    }

    fun updateBuShu(bushu: Int) {
        tvCount.text = bushu.toString()
        dashBoard.updateProgress(bushu)
        GUtils.updateDistanceAndEnergyUI(AppUtil.user.bs,tvDistance,tvSpendTime,tvEnergy)

        if (!GUtils.dashBoardAnimated){
            GUtils.dashBoardAnimated = true
            dashBoard.anim()
        }
    }

//    private fun updateTodayData() {
//        val user = AppUtil.user
//        // 每步 0.52m
//        // 每秒 1.66步
//        // 每步 消耗 0.03千卡
//        tvDistance.text = String.format("%.2f", user.bs * GUtils.MeterPerBu / 1000f)
//
//        // 超过1个小时,就使用  18sp
//        val timeSeconds = (user.bs / 1.66f).toLong()
//        if (timeSeconds < 3600) {
//            tvSpendTime.text = MyTimeUtils.format_mmss(timeSeconds * 1000)
//        } else {
//            tvSpendTime.text = MyTimeUtils.format_HHmmss(timeSeconds * 1000)
//        }
//
//        // 卡路里
//        tvEnergy.text = String.format("%.2f", user.bs * 0.03f)
//    }

    //==========================
    fun btnHbyClicked(){
        if (!isReady){
            return
        }
        if (AppUtil.isHbyTodayCompleted()){
            AppUtil.toast("今日已达上限!")
            return
        }
        if (AppUtil.isHbyCanPlay()){
            startToActivity(HbyGame::class.java)
        }else{
            AppUtil.toast("时间还未到!")
        }
    }

    fun btnReloginClicked(){
        val loading = LoadingDialog(requireActivity(),"登陆中...")
        loading.show()

        val userModel = AppUtil.appViewModel()
        userModel.login2(AppUtil.user.bs_sys) { success ->
            loading.dismiss()
            if (success) {
                rlError.visibility = View.GONE
                fetchInfo()
            } else {
                // 还是登陆失败
                rlError.visibility = View.VISIBLE
            }
        }
    }
}